package com.qs.education.service.impl;

import java.util.ArrayList;
import java.util.List;
import javax.transaction.Transactional;

import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import com.qs.education.bean.api.ResponseBean;
import com.qs.education.bean.api.ResponseListBean;
import com.qs.education.bean.beans.EducationHomeWorkResponse;
import com.qs.education.bean.beans.EducationHomeWorkStudentResponse;
import com.qs.education.bean.entity.EducationGroup;
import com.qs.education.bean.entity.EducationAnswer;
import com.qs.education.bean.entity.EducationHomeWork;
import com.qs.education.bean.entity.EducationHomeWorkQuestion;
import com.qs.education.bean.entity.EducationHomeWorkStudent;
import com.qs.education.bean.entity.EducationQuestion;
import com.qs.education.bean.entity.EducationStudent;
import com.qs.education.bean.entity.EducationStudentQuestion;
import com.qs.education.bean.entity.EducationSubjectLesson;
import com.qs.education.bean.entity.EducationTeacher;
import com.qs.education.bean.enums.ResponseStatus;
import com.qs.education.bean.service.BaseService;
import com.qs.education.service.IHomeWorkAPIService;

@Service
public class HomeWorkServiceImpl extends BaseService implements IHomeWorkAPIService {

	/**
	 * @author Warren
	 * @param studentId
	 * @return ResponseListBean<EducationHomeWorkStudent>
	 * @description 根据学生id查询学生的作业列表(作业本)
	 * @date Nov 20, 2018
	 */
	@Override
	public ResponseListBean<EducationHomeWorkStudent> getListByStudentId(Long studentId) {
		ResponseListBean<EducationHomeWorkStudent> responseListBean = new ResponseListBean<EducationHomeWorkStudent>();
		EducationStudent educationStudent = iEducationStudentDao.get(EducationStudent.class, studentId);
		List<EducationHomeWorkStudent> list = iEducationHomeWorkStudentDao.getListByStudentId(educationStudent);
		responseListBean.setList(list);
		return responseListBean;
	}

	/**
	 * @author Warren
	 * @param homeworkId
	 * @return ResponseListBean<EducationHomeWorkQuestion>
	 * @description 根据作业id获得作业的所有题目
	 * @date Nov 22, 2018
	 */
	@Override
	public ResponseListBean<EducationHomeWorkQuestion> getALLQuestionByHomeWorkId(Long homeworkId) {
		ResponseListBean<EducationHomeWorkQuestion> responseListBean = new ResponseListBean<EducationHomeWorkQuestion>();
		EducationHomeWork educationHomeWork = iEducationHomeWorkDao.get(EducationHomeWork.class, homeworkId);
		List<EducationHomeWorkQuestion> list = iEducationHomeWorkQuestionDao
				.getALLQuestionByHomeWorkId(educationHomeWork);
		if (list != null) {
			responseListBean.setList(list);
			for (EducationHomeWorkQuestion eq : list) {
				eq.setHomework(null);
			}
		}
		return responseListBean;
	}

	/**
	 * @author Warren
	 * @param hqId      作业问题标识
	 * @param studentId 学生id
	 * @param answerId  问题选项id
	 * @return ResponseBean
	 * @description
	 * @date Nov 22, 2018
	 */
	@Transactional
	@Override
	public ResponseBean answerHomeWorkQuestion(Long hqId, Long studentId, Long answerId) {
		ResponseBean responseBean = new ResponseBean();
		EducationStudentQuestion educationStudentQuestion = new EducationStudentQuestion();
		educationStudentQuestion.setAnswer(iEducationAnswerDao.get(EducationAnswer.class, answerId));
		educationStudentQuestion.setStudent(iEducationStudentDao.get(EducationStudent.class, studentId));
		educationStudentQuestion
				.setHomeworkQuestion(iEducationHomeWorkQuestionDao.get(EducationHomeWorkQuestion.class, hqId));
		boolean result = iEducationStudentQuestionDao.save(educationStudentQuestion);
		if (result) {
			responseBean.setStatus(ResponseStatus.SUCCESS.toString());
		} else {
			responseBean.setStatus(ResponseStatus.FAILED.toString());
		}
		return responseBean;
	}

	/**
	 * @author Warren
	 * @param homeworkId
	 * @param studentId
	 * @param startTime
	 * @param endTime
	 * @return ResponseBean
	 * @description 学生提交作业
	 * @date Nov 22, 2018
	 */
	@Transactional
	@Override
	public ResponseBean studentCommitHomeWork(Long homeworkId, Long studentId, String startTime, String endTime) {
		ResponseBean responseBean = new ResponseBean();
		EducationStudent educationStudent = iEducationStudentDao.get(EducationStudent.class, studentId);
		EducationHomeWork educationHomeWork = iEducationHomeWorkDao.get(EducationHomeWork.class, homeworkId);
		EducationHomeWorkStudent educationHomeWorkStudent = iEducationHomeWorkStudentDao

				.findEducationHomeWorkStudentByStudentAndHomeWork(educationStudent, educationHomeWork);
		educationHomeWorkStudent.setStartTime(startTime);
		educationHomeWorkStudent.setEndTime(endTime);
		List<EducationHomeWorkQuestion> educationHomeWorkQuestionList = educationHomeWork.getHomeWorkQuestionList();
		// 一份作业回答正确的题目数量
		double correctAnswerCount = 0;
		for (EducationHomeWorkQuestion ehq : educationHomeWorkQuestionList) {
			// 获得当前题目
			EducationQuestion educationQuestion = ehq.getQuestion();
			// 获得题目的正确答案
			String correctAnswer = educationQuestion.getCorrectAnswer();
			EducationStudentQuestion educationStudentQuestion = iEducationStudentQuestionDao
					.findEducationStudentQuestionByStudentAndHomeWorkQuestion(educationStudent, ehq);
			// 获得学生作答该题目的答案
			String studentAnswer = educationStudentQuestion.getAnswer().getDescription();
			if (correctAnswer.equals(studentAnswer)) {
				correctAnswerCount++;
				educationQuestion.setCorrectCount(educationQuestion.getCorrectCount() + 1);
				iEducationQuestionDao.save(educationQuestion);
			} else {
				educationQuestion.setErrorCount(educationQuestion.getErrorCount() + 1);
				iEducationQuestionDao.save(educationQuestion);
			}
		}
		double CorrectRate = correctAnswerCount / educationHomeWorkQuestionList.size();
		educationHomeWorkStudent.setCorrectRate((double) Math.round(CorrectRate * 100) / 100);
		iEducationHomeWorkStudentDao.save(educationHomeWorkStudent);

		double classCorrectRate = 0;
		List<EducationHomeWorkStudent> educationHomeWorkStudentList = iEducationHomeWorkStudentDao
				.findEducationHomeWorkStudentByHomeWork(educationHomeWork);
		for (EducationHomeWorkStudent ehs : educationHomeWorkStudentList) {
			classCorrectRate += ehs.getCorrectRate();
		}
		classCorrectRate = classCorrectRate / educationHomeWork.getGroup().getStudents().size();
		educationHomeWork.setCorrectRate((double) Math.round(classCorrectRate * 100) / 100);
		iEducationHomeWorkDao.save(educationHomeWork);
		responseBean.setStatus(ResponseStatus.SUCCESS.toString());
		return responseBean;
	}

	// ------------------------------------------------------------------------------------------------------------
	/**
	 * @Description 教师选择群组发布作业
	 * @Description 分割方法 将 三个数据库操作 分别放到三个方法中
	 * @Description 1. 先根据teacherID 获取 教师
	 * @Description 2. 根据 groupIds 获取所需要发布的全部群组
	 * @Description 3. 根据群组的数量创建homeWork 存入education_homework数据库
	 * @author Leon
	 * @date Nov 22, 2018
	 * @param
	 * @return ResponseBean
	 */
	@Transactional
	@Override
	public void publishHomeWork(List<Long> questionIds, List<Long> groupIds, List<Long> lessonIds, String startTime,
			String endTime, String teacherId) {
		// 1. 先根据teacherID 获取 教师
		EducationTeacher teacher = iEducationTeacherDao.get(EducationTeacher.class, Integer.parseInt(teacherId));
		// 2. 根据 groupIds 获取所需要发布的全部群组
		List<EducationGroup> groups = iEducationGroupDao.getGroupsByIds(groupIds);

		// 2.1 （新增） 根据lessonIds 获取所需要发布的SubjectLesson
		List<EducationSubjectLesson> lessons = iEducationSubjectLessonDao.getLessonByIds(lessonIds);
		// 3. 根据群组的数量创建 homeWork 存入education_homework数据库
		List<EducationHomeWork> homeworkList = new ArrayList<EducationHomeWork>();
		for (EducationGroup group : groups) {
			EducationHomeWork homeWork = new EducationHomeWork();
			homeWork.setSubjectLessonList(lessons);
			homeWork.setStartTime(startTime);
			homeWork.setEndTime(endTime);
			homeWork.setGroup(group);
			homeWork.setTeacher(teacher);
			homeworkList.add(homeWork);
		}
		// education_homework 的批量添加
		iEducationHomeWorkDao.batchInsert(homeworkList);
		batchInsertHomeWorkQuestion(questionIds, homeworkList);
		batchInsertHomeWorkStudent(homeworkList);
	}

	/**
	 * @Description education_homework_question 的批量添加
	 * @Description 4. 根据questionIds 获取所有的题目
	 * @Description 5. 再根据题目数量创建homework_question 然后存入homework_question数据库
	 * @author Leon
	 * @date Nov 22, 2018
	 * @param
	 * @return void
	 */
	@Transactional
	public void batchInsertHomeWorkQuestion(List<Long> questionIds, List<EducationHomeWork> homeworkList) {
		List<EducationHomeWorkQuestion> homeworkQuestionList = new ArrayList<EducationHomeWorkQuestion>();
		List<EducationQuestion> questions = iEducationHomeWorkDao.getQuestionByIds(questionIds);
		for (EducationHomeWork homeWork : homeworkList) {
			for (EducationQuestion question : questions) {
				EducationHomeWorkQuestion homeworkQuestion = new EducationHomeWorkQuestion();
				homeworkQuestion.setHomework(homeWork);
				homeworkQuestion.setQuestion(question);
				homeworkQuestionList.add(homeworkQuestion);
			}
		}
		// education_homework_question 的批量添加
		iEducationHomeWorkQuestionDao.batchInsert(homeworkQuestionList);
	}

	/**
	 * 
	 * @Description education_homework_student 的批量添加
	 * @Description 6. 根据选中的groups获取groups所有的students
	 * @Description 7.创建educationhomeworkstudent对象 存入education_homework_student数据表中
	 * @author Leon
	 * @date Nov 22, 2018
	 * @param
	 * @return void
	 */
	@Transactional
	public void batchInsertHomeWorkStudent(List<EducationHomeWork> homeworks) {
		List<EducationHomeWorkStudent> homeworkStudents = new ArrayList<EducationHomeWorkStudent>();
		for (EducationHomeWork homeworkS : homeworks) {
			EducationGroup group = homeworkS.getGroup();
			List<EducationStudent> students = group.getStudents();
			for (EducationStudent student : students) {
				EducationHomeWorkStudent homeworkStudent = new EducationHomeWorkStudent();
				homeworkStudent.setHomework(homeworkS);
				homeworkStudent.setStudent(student);
				homeworkStudents.add(homeworkStudent);
			}
		}
		// education_homework_student 的批量添加
		iEducationHomeWorkStudentDao.batchInsert(homeworkStudents);
	}

	/**
	 * @Description 根据教师ID查询作业列表
	 * @author Leon
	 * @date Nov 23, 2018
	 * @param
	 * @return ResponseListBean<EducationHomeWork>
	 */
	@Override
	public ResponseListBean<EducationHomeWork> findHomeWorkByTeacherId(String teacherId) {
		ResponseListBean<EducationHomeWork> response = new ResponseListBean<EducationHomeWork>();
		try {
			List<EducationHomeWork> homeworks = iEducationHomeWorkDao.findHomeWorkByTeacherId(teacherId);
			for (EducationHomeWork homework : homeworks) {
				homework.setHomeWorkQuestionList(null);
				homework.setHomeWorkStudentList(null);
			}
			response.setList(homeworks);
			response.setStatus(ResponseStatus.SUCCESS.toString());
		} catch (Exception e) {
			response.setStatus(ResponseStatus.SUCCESS.toString());
			e.printStackTrace();
		}
		return response;
	}

	/**
	 * @Description 根据作业id 查看作业概览
	 * @author Leon
	 * @date Nov 26, 2018
	 * @param
	 * @return EducationHomeWorkResponse
	 */
	@Override
	public EducationHomeWorkResponse findHomeWorkOverviewById(String id) {
		EducationHomeWorkResponse response = new EducationHomeWorkResponse();
		EducationHomeWork homework = new EducationHomeWork();
		homework = iEducationHomeWorkDao.get(EducationHomeWork.class, Long.parseLong(id));
		if (homework != null) {
			try {
				BeanUtils.copyProperties(homework, response);
				
			} catch (Exception e) {
				response.setStatus(ResponseStatus.FAILED.toString());
				e.printStackTrace();
			}
		} else {
			response.setStatus(ResponseStatus.FAILED.toString());
			response.setMessage("该作业不存在");
		}
		return response;
	}

	/**
	 * @Description 根据作业id删除作业
	 * @author Leon
	 * @date Nov 26, 2018
	 * @param
	 * @return ResponseBean
	 */
	@Transactional
	@Override
	public ResponseBean deleteHomeWorkById(String id) {
		ResponseBean response = new ResponseBean();
		EducationHomeWork homework = iEducationHomeWorkDao.get(EducationHomeWork.class, Long.parseLong(id));
		if (homework == null) {
			response.setStatus(ResponseStatus.FAILED.toString());
			response.setMessage("该作业不存在");
		} else {
			List<Long> studentIds = new ArrayList<Long>();
			List<Long> questionIds = new ArrayList<Long>();
			List<EducationHomeWorkStudent> students = new ArrayList<EducationHomeWorkStudent>();
			List<EducationHomeWorkQuestion> questions = new ArrayList<EducationHomeWorkQuestion>();
			students = homework.getHomeWorkStudentList();
			questions = homework.getHomeWorkQuestionList();
			for (EducationHomeWorkStudent student : students) {
				studentIds.add(student.getId());
			}
			for (EducationHomeWorkQuestion question : questions) {
				questionIds.add(question.getId());
			}
			iEducationHomeWorkDao.delete(homework);
			for (Long studentId : studentIds) {
				iEducationHomeWorkStudentDao.delete(studentId, EducationHomeWorkStudent.class);
			}
			for (Long questionId : questionIds) {
				iEducationHomeWorkQuestionDao.delete(questionId, EducationHomeWorkQuestion.class);
			}
		}
		return response;
	}

	/**
	 * @Description 获取学生作业概览
	 * @author Leon
	 * @date   Nov 27, 2018
	 * @param  
	 * @return EducationHomeWorkStudentResponse
	 */
	@Override
	public EducationHomeWorkStudentResponse getStudentHomeWorkOverview(String id) {
		EducationHomeWorkStudentResponse response = new EducationHomeWorkStudentResponse();
		EducationHomeWorkStudent homeWorkStudent = iEducationHomeWorkStudentDao.get(EducationHomeWorkStudent.class, Long.parseLong(id));
		if(homeWorkStudent != null) {
			BeanUtils.copyProperties(homeWorkStudent, response);
		}
		return null;	
	}
}
